import type { RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHashHistory } from 'vue-router'
import Layout from '../components/layout/index.vue'


const routes: RouteRecordRaw[] = [
    {
        path: '/',
        component: Layout,
        children: [
            {
                path: '/home',
                name: '主页',
                meta: {
                    title: '主页',
                },
                component: () => import('../pages/home/index.vue')
            },
            {
                path: '/car',
                name: '车辆',
                meta: {
                    title: '车辆',
                },
                component: () => import('../pages/car/index.vue')
            },
            {
                path: '/user',
                name: '用户',
                meta: {
                    title: '用户',
                },
                component: () => import('../pages/user/index.vue')
            },
        ]
    },
    {
        path: '/login',
        component: () => import('../pages/login/index.vue'),
        meta: {
            title: '登录',
        },
    },
    {
        path: '/register',
        component: () => import('../pages/register/index.vue'),
        meta: {
            title: '注册',
        },
    },
]

const router = createRouter({
    history: createWebHashHistory(),
    routes,
    // 切换页面，滚动到最顶部
    scrollBehavior: () => ({ left: 0, top: 0 }),
})
// let whiteList = ['/login','/register']
let whiteList = ['/login','/register','/home', '/user', '/car']

router.beforeEach(async (to, from, next) => {
    const hasToken = sessionStorage.getItem('token')
    console.log("from ==>", from)
    console.log("to ==>", to)
    if (to.meta.title) {
        document.title = to.meta.title;
      } else {
        document.title = '后台';
      }
    if(hasToken) {
        if(to.path === '/login') {
            next('/')
        } else {
            next()
        }
    } else {
        if (whiteList.indexOf(to.path) >= 0) { // 不需要登录
            console.log("to ==> 333")
            next()
        } else {
            console.log("to ==> 444")
            next('/login')
        }
    }
    next()
})


export { router, routes }